# -*- coding: utf-8 -*-
# @Author  : Lison Song
# @Time    : 2023/3/24 16:26
import json
import logging
from datetime import datetime, timedelta
from flask import Blueprint, render_template, request, session, jsonify, current_app
from flask_login import login_required, current_user
from sqlalchemy import desc, func
from applications.common.utils.validate import str_escape
from applications.common.utils.http import table_api, fail_api, success_api, success_dataList_api, success_data_api
from applications.extensions import db
from applications.models import Weixin_articles, Weixin_Official_Acc, Weixin_Official_Acc_log
from applications.common.utils.mytools import MyTools
from applications.models.admin_robot_info import Robot_Info
import time

data_analysis_bp = Blueprint('dataAnalysis', __name__, url_prefix='/api/dataAnalysis')


@data_analysis_bp.get('/logstream')
@login_required
def logstream():
    '''
    为首页 提供 机器人 采集动态数据
    :return:
    '''
    limit_num = 300
    try:
        limit_num = int(str_escape(request.args.get('limitNum', type=str)))
    except Exception as e:
        current_app.logger.error(f"未传入limitNum 参数:{e}")
    if limit_num == 0:
        limit_num = 300
    oaquery = db.session.query(
        Weixin_Official_Acc_log.article_nu, Weixin_Official_Acc_log.indb_nu, Weixin_Official_Acc_log.wx_id,
        Weixin_Official_Acc.wx_name,
        Robot_Info.name, Weixin_Official_Acc_log.update_at, Weixin_Official_Acc_log.elapsed_time
    ).filter(Weixin_Official_Acc_log.wx_id == Weixin_Official_Acc.id,
             Weixin_Official_Acc_log.robot_id == Robot_Info.id).order_by(
        Weixin_Official_Acc_log.update_at.desc()).limit(limit_num).all()
    data = []
    for item in oaquery:
        datetimestr = datetime.strftime(item.update_at, "%Y-%m-%d %H:%M:%S")
        log_item = {}
        log_item['robot_name'] = item.name
        log_item['update_at'] = datetimestr
        log_item['article_nu'] = item.article_nu
        log_item['wx_name'] = item.wx_name
        log_item['desc'] = f"耗时{item.elapsed_time}秒,采集公众号 【{item.wx_name}】{item.article_nu} 篇，入库 {item.indb_nu} 篇"
        data.append(log_item)
        # print(type(datetime.strftime(item.update_at, "%Y-%m-%d %H:%M:%S")))

    return success_dataList_api(msg="成功", dataList=data)


@data_analysis_bp.get('/consoledata')
@login_required
def consoledata():
    '''
    为首页数字块提供数据
    :return:
    '''
    article_all = Weixin_articles.query.count()
    offAcc_all = Weixin_Official_Acc.query.count()
    todaystr = MyTools.getTodaydatestr()
    # todaystr = "2023-07-18"
    today_article_nu = db.session.query(func.sum(Weixin_Official_Acc_log.article_nu)).filter(
        Weixin_Official_Acc_log.day == todaystr).scalar()
    today_article_indb_nu = db.session.query(func.sum(Weixin_Official_Acc_log.indb_nu)).filter(
        Weixin_Official_Acc_log.day == todaystr).scalar()
    # print(f" lison print : {article_all} {offAcc_all} {today_article_nu} {today_article_indb_nu}")
    if today_article_nu:
        today_article_nu = int(today_article_nu)
    else:
        today_article_nu = 0
    if today_article_indb_nu:
        today_article_indb_nu = int(today_article_indb_nu)
    else:
        today_article_indb_nu = 0
    result = {}
    result['article_all'] = article_all
    result['offAcc_all'] = offAcc_all
    result['today_article_nu'] = today_article_nu
    result['today_article_indb_nu'] = today_article_indb_nu
    result['todaystr'] = todaystr

    return success_data_api(msg="成功", data=result)


@data_analysis_bp.get('/collectAnalysis')
@login_required
def collectAnalysis():
    '''
    按天 统计采集结果
    :parameter days 从当天日期向前推算的天数 int
    :return:
    '''
    days = 7
    try:
        days = int(str_escape(request.args.get('days', type=str)))
    except Exception as e:
        return fail_api(msg=f"参数异常{str(e)}")

    query = db.session.query(Weixin_Official_Acc_log.day,
                             func.sum(Weixin_Official_Acc_log.article_nu).label('collectnum'),
                             func.sum(Weixin_Official_Acc_log.indb_nu).label('indbnum')).group_by(
        Weixin_Official_Acc_log.day).order_by(Weixin_Official_Acc_log.day.desc()).limit(days).all()
    # print(query)
    dbdataDicList = []
    for item in query:
        itemDic = {}
        itemDic['datestr'] = datetime.strftime(item.day, "%Y-%m-%d")
        itemDic['collectnum'] = item.collectnum
        itemDic['indbnum'] = item.indbnum
        # print(datetime.strftime(item.day, "%Y-%m-%d"), item.allnum, item.indbnum)
        dbdataDicList.append(itemDic)
    # dbdataDicList.sort(key=lambda x: x[0], reverse=True)
    # 逆序结果
    data = dbdataDicList[::-1]
    return success_dataList_api(msg="成功", dataList=data)
